<template>
    <div class="city-search">
        <input
            type="text"
            class="ipt-search"
            placeholder="输入城市名或拼音"
            v-model="keyword"
        >
        <div class="search-content" ref="searchList" v-show="keyword">
            <ul>
                <li
                    v-for="item of list"
                    :key="item.id"
                    class="search-item border-bottom"
                    @click="handleClickCity(item.name)"
                >{{item.name}}</li>
                <li class="search-item border-bottom" v-show="noData">没有找到匹配数据</li>
            </ul>
        </div>
    </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 如果搜索框内容为空,那清空搜索列表的数据
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (const i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        // console.log(result)
        this.list = result
      }, 100)
    }
  },
  mounted () {
    //   搜索列表内容超出滚动
    this.scroll = new Bscroll(this.$refs.searchList)
  },
  computed: {
    noData () {
      return !this.list.length
    }
  },
  methods: {
    handleClickCity (city) {
      this.$store.commit('mCity', city)
      this.$router.push('/')
    }
  }
}
</script>

<style  lang="stylus" scoped>
    @import '~styles/variables.styl'
    .border-bottom
        &:before
            border-color #666
    .city-search
        height .72rem
        padding 0 .1rem
        background $bgColor
        .ipt-search
            box-sizing border-box
            padding 0 .1rem
            width 100%
            height .64rem
            line-height .64rem
            text-align center
            border-radius .06rem
            color #666
        .search-content
            z-index 1
            overflow hidden
            position absolute
            top 1.6rem
            right 0
            bottom 0
            left 0
            background #eee
            .search-item
                line-height .64rem
                padding-left .2rem
                color #666
                background #fff

</style>
